package com.example.topguli;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadIntenet {
    public static void main(String[] args) {
        CommonBuffer commonBuffer = new CommonBuffer();
        Producter producter = new Producter(commonBuffer);
        Consumer consumer = new Consumer(commonBuffer);
        new Thread(producter,"生产者").start();
        new Thread(producter,"生产者1").start();
        new Thread(consumer,"消费者").start();
        new Thread(consumer,"消费者1").start();
    }
}
class  Producter implements Runnable{
    private CommonBuffer commonBuffer;
    public Producter(CommonBuffer commonBuffer){
        this.commonBuffer=commonBuffer;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                commonBuffer.incNum();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Consumer implements  Runnable{
    private CommonBuffer commonBuffer;
    public Consumer(CommonBuffer commonBuffer){
        this.commonBuffer=commonBuffer;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                commonBuffer.descNum();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class CommonBuffer{
    private Integer num=0;
    ReentrantLock lock=new ReentrantLock();
    Condition condition = lock.newCondition();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    private Integer flag=1;
    public  void incNum() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0) {
//                this.wait();
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+(++num));
//            this.notifyAll();
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public  Integer descNum() throws InterruptedException {
        lock.lock();
        try {
            while (num==0){
//                this.wait();
               condition.await();
            }
            System.out.println(Thread.currentThread().getName()+(num--));
//            this.notifyAll();
            condition.signalAll();

        }catch (Exception e){

        }finally {
            lock.unlock();
            return num;
        }
    }

}
